﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace LightLibrary {
	public partial class FormMain : Form {
		// === VisualStudio ===========================================================================================
		public FormMain() {
			InitializeComponent();
			// menu tabs
			Library.Instance.AddListener(RefreshMenuTabs);
			RefreshMenuTabs();
			// lib view
			LibView.Columns.AddRange(TableTools.GetColumnsForBooks());
			Library.Instance.AddListener(RefreshLibView);
			RefreshLibView();
		}

		// === Private ================================================================================================
		private Dictionary<DataGridViewRow, Asset> _assetsByRow = new Dictionary<DataGridViewRow, Asset>();

		private void AddAssetToTable(Asset asset) {
			if(asset == null) {
				throw new Exception("FI is null");
			}
			var row = Factory.CreateLibRow(LibView, asset);
			LibView.Rows.Add(row);
			_assetsByRow.Add(row, asset);
		}

		private void FilesListView_CellClick(object sender, DataGridViewCellEventArgs e) {
			// Ignore clicks that are not on button cells.  
			if(e.ColumnIndex != LibView.Columns["ColumnLaunch"].Index) {
				return;
			}
			var row = LibView.Rows[e.RowIndex];
			var asset = _assetsByRow[row];
			Process.Start(asset.FileInfo.FullName);
		}

		#region menu
		private void MenuLibNewClick(object sender, EventArgs e) {
			var formLibraryNew = new FormLibraryNew {
				StartPosition = FormStartPosition.CenterParent
			};
			formLibraryNew.ShowDialog(this);
			if(formLibraryNew.NewLibrary != null) {
				Library.Instance.SetWorkLibrary(formLibraryNew.NewLibrary);
			}
		}

		private void MenuLibOpenClick(object sender, EventArgs e) {
			var formLibraryOpen = new FormLibraryOpen() {
				StartPosition = FormStartPosition.CenterParent
			};
			formLibraryOpen.ShowDialog();
			if(formLibraryOpen.OpenedLibrary != null) {
				Library.Instance.SetWorkLibrary(formLibraryOpen.OpenedLibrary);
			}
		}

		private void MenuLibSave(object sender, EventArgs e) {
			Library.Instance.Work.SaveToDiskAsXml();
		}

		private void MenuLibCloseClick(object sender, EventArgs e) {
			Library.Instance.SaveAndCloseLibrary();
		}

		private void MenuLibExitClick(object sender, EventArgs e) {
			Library.Instance.SaveAndCloseLibrary();
			Application.Exit();
		}

		private void MenuToolsScanForAssetsClick(object sender, EventArgs e) {
			var scanDirPath = IOTools.GetDirectoryPath();
			if(string.IsNullOrEmpty(scanDirPath)) {
				return;
			}
			var scanDi = new DirectoryInfo(scanDirPath);
			var files = new List<FileInfo>();
			files.AddRange(IOTools.GetFilesByExtensions(scanDi, ExtensionTools.GetExtensions(ExtensionTypeGroup.Book)));
			files.Sort((info, fileInfo) => String.Compare(info.Name, fileInfo.Name, StringComparison.Ordinal));

			var formScan = new FormScan(files) {
				StartPosition = FormStartPosition.CenterParent
			};
			formScan.ShowDialog();
			Library.Instance.Work.AddAssets(formScan.Files);
			RefreshLibView();
		}

		private void MenuHelpAboutClick(object sender, EventArgs e) {
			var about = new FormAbout();
			about.ShowDialog();
		}

		private void RefreshMenuTabs() {
			if(Library.Instance.Work == null) {
				DisableAdditionalMenuTabs();
			} else {
				EnableAdditionalMenuTabs();
			}
		}

		private void DisableAdditionalMenuTabs() {
			MenuTabsEnabled(false);
		}

		private void EnableAdditionalMenuTabs() {
			MenuTabsEnabled(true);
		}

		private void MenuTabsEnabled(bool enabled) {
			menuLibSave.Enabled = enabled;
			menuLibClose.Enabled = enabled;
			menuToolsScanForAssets.Enabled = enabled;
			MenuToolsDel.Enabled = enabled;
		}
		#endregion

		#region View
		public void RefreshLibView() {
			LibView.Rows.Clear();
			_assetsByRow.Clear();
			LibView.Visible = Library.Instance.Work != null;
			if(!LibView.Visible) {
				return;
			}
			foreach(var asset in Library.Instance.Work.GetAssets()) {
				AddAssetToTable(asset);
			}
		}
		#endregion

		private void FormMain_FormClosing(object sender, FormClosingEventArgs e) {
			Library.Instance.SaveAndCloseLibrary();
		}

		private void MenuToolsDelClick(object sender, EventArgs e) {
			LibView.EndEdit();
			foreach(var row in _assetsByRow.Keys) {
				if(bool.Parse(row.Cells["ColumnSelect"].Value.ToString())) {
					Library.Instance.Work.RemoveAssets(_assetsByRow[row]);
				}
			}
			RefreshLibView();
		}

		private void LibViewDoubleClick(object sender, EventArgs e) {
			if(LibView.SelectedCells.Count != 1) {
				MessageBox.Show("Must be select only one row");
				return;
			}
			var selectedRow = LibView.Rows[LibView.SelectedCells[0].RowIndex];
			var asset = _assetsByRow[selectedRow];
			var formAssetEdit = Factory.CreateFormAssetEdit(asset);
			formAssetEdit.ShowDialog();
			if(formAssetEdit.ResultOk) {
				RefreshLibView();
			}
		}
	}
}
